package com.sccl.iottm.service.impl;

import com.sccl.iottm.dao.PermissionDao;
import com.sccl.iottm.dao.UserRepository;
import com.sccl.iottm.entity.User;
import com.sccl.iottm.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Dave
 * @Date 2018/9/6
 * @Description
 */

@Service
public class UserServiceImpl implements UserService {
    private final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserRepository userRepository;
    @Autowired
    PermissionDao permissionDao;
    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public void addUser(User user) {
        userRepository.save(user);
    }

    @Override

    public User findUser(String name, String pwd) {
        return userRepository.findByNameAndPassword(name, pwd);
    }

    @Override
    public User findUserByName(String name) {
        return userRepository.findUserByName(name);
    }


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userRepository.findUserByName(s);
        if (user != null) {
            //拿到当前用户的所有会话 需要重写user的equal方法
            List<SessionInformation> allSessions = sessionRegistry.getAllSessions(user, true);
            //将之前的用户挤下线
            allSessions.forEach(SessionInformation::expireNow);
            return user;

        } else {
            throw new UsernameNotFoundException("user" + s + " do not exist!");

        }
    }
}
